const app = getApp();

export function validateCanGetRefreshToken(refreshToken, expiresTime) {
  const token = wx.getStorageSync("token");
  if (refreshToken && expiresTime < Date.now() + 30000) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: app.globalData.baseURL + "/app-user-api/member/auth/refresh-token",
        method: "POST",
        header: {
          "Authorization": `Bearer ${token}`,
          "tenant-id": 156,
          "Content-Type": "application/x-www-form-urlencoded",
          "login_user_type":3
        },
        data: {
          refreshToken: refreshToken,
        },
        success: (res) => {
          // 服务器返回新的 token
          const newToken = res.data.data.accessToken;
          // 更新本地存储的 token
          wx.setStorageSync("token", newToken);
          wx.setStorageSync("expiresTime", res.data.data.expiresTime);
          wx.setStorageSync("refreshToken", res.data.data.refreshToken);
          // 返回新的 token在请求拦截器中使用
          resolve(newToken);
        },
        fail: (err) => {
          // 刷新 token 失败
          console.error("刷新 token 失败", err);
          wx.removeStorageSync("token");
          reject(err)
        },
      });
    });
  } else {
    return Promise.resolve(token);
  }
}
